(function (window) {
  // 如果plus已经存在，直接返回
  if (window.plus) {
    return;
  }

  // 创建一个管理所有webview的容器
  const webviewMap = new Map();

  window.plus = {
    isH5: true,

    os: {
      name: /iPhone|iPad|iPod/i.test(navigator.userAgent) ? 'iOS' : 'Android',
      version: '1.0.0',
      vendor: 'h5-vendor',
      language: navigator.language
    },

    webview: {
      currentWebview() {
        return {
          close() {
            history.back()
          },
          show() {
            const currentIframe = this.iframe;
            if (currentIframe) {
              // 隐藏其他所有iframe
              webviewMap.forEach((webview) => {
                if (webview.iframe !== currentIframe) {
                  webview.iframe.style.display = 'none';
                }
              });
              // 显示当前iframe
              currentIframe.style.display = 'block';
            }
          },
          hide() {
            if (this.iframe) {
              this.iframe.style.display = 'none';
            }
          },
          setStyle() { },
          append(webview) {
            if (webview?.iframe) {
              const container = document.querySelector('.mui-content') || document.body;
              container.appendChild(webview.iframe);
            }
          },
          // 添加事件监听相关方法
          addEventListener(type, listener) {
            if (this.iframe) {
              this.iframe.addEventListener(type, listener);
            }
          },
          removeEventListener(type, listener) {
            if (this.iframe) {
              this.iframe.removeEventListener(type, listener);
            }
          },
          dispatchEvent(event) {
            if (this.iframe) {
              this.iframe.dispatchEvent(event);
            }
          }
        }
      },

      create(url, id, styles = {}) {
        // 如果已存在相同id的webview，先移除
        const existingWebview = webviewMap.get(id);
        if (existingWebview) {
          existingWebview.iframe.remove();
          webviewMap.delete(id);
        }

        const iframe = document.createElement('iframe');
        iframe.src = url;
        iframe.id = id;
        
        // 转换样式对象为像素值
        const pixelStyles = {};
        for (let key in styles) {
          if (typeof styles[key] === 'number' || /^\d+$/.test(styles[key])) {
            pixelStyles[key] = styles[key] + 'px';
          } else {
            pixelStyles[key] = styles[key];
          }
        }

        // 设置基础样式
        let baseStyles = {
          position: 'absolute',
          width: '100%',
          border: 'none',
          left: '0',
          display: 'none'
        };

        // 登录页面特殊处理
        if (id === 'login.html') {
          baseStyles = {
            ...baseStyles,
            position: 'fixed',
            top: '0',
            left: '0',
            right: '0',
            bottom: '0',
            width: '100%',
            height: '100%',
            border: 'none',
            display: 'block',
            zIndex: '10001',
            backgroundColor: '#fff'
          };
          // 直接应用样式
          Object.assign(iframe.style, baseStyles);
          
          // 创建一个遮罩层，防止mui-bar显示
          const mask = document.createElement('div');
          mask.id = 'login-mask';
          mask.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: #fff;
            z-index: 10000;
          `;
          document.body.appendChild(mask);
          
          // 在登录页面关闭时移除遮罩
          iframe.addEventListener('close', () => {
            mask.remove();
          });
        } else {
          // 非登录页面
          baseStyles.height = `calc(100% - ${styles.top || '0'} - ${styles.bottom || '0'})`;
          // 应用基础样式和自定义样式
          Object.assign(iframe.style, baseStyles, pixelStyles);
        }

        const webviewObj = {
          id: id,
          iframe: iframe,
          show() {
            // 隐藏其他所有iframe
            webviewMap.forEach((webview) => {
              if (webview !== this) {
                webview.iframe.style.display = 'none';
              }
            });
            // 显示当前iframe
            iframe.style.display = 'block';
            // 触发show事件
            this.dispatchEvent(new CustomEvent('show'));
          },
          hide() {
            iframe.style.display = 'none';
            // 触发hide事件
            this.dispatchEvent(new CustomEvent('hide'));
          },
          close() {
            // 触发close事件
            this.dispatchEvent(new CustomEvent('close'));
            iframe.remove();
            webviewMap.delete(id);
          },
          // 添加事件监听相关方法
          addEventListener(type, listener) {
            if (!this._listeners) this._listeners = new Map();
            if (!this._listeners.has(type)) {
              this._listeners.set(type, new Set());
            }
            this._listeners.get(type).add(listener);
          },
          removeEventListener(type, listener) {
            if (this._listeners?.has(type)) {
              this._listeners.get(type).delete(listener);
            }
          },
          dispatchEvent(event) {
            if (this._listeners?.has(event.type)) {
              this._listeners.get(event.type).forEach(listener => {
                listener.call(this, event);
              });
            }
          }
        };

        // 将webview对象存储到Map中
        webviewMap.set(id, webviewObj);

        return webviewObj;
      },

      getWebviewById(id) {
        return webviewMap.get(id) || null;
      }
    },

    // 添加navigator相关接口
    navigator: {
      closeSplashscreen() {
        // H5环境下可以隐藏启动页
        const splash = document.getElementById('splash')
        if (splash) {
          splash.style.display = 'none'
        }
      }
    },

    // 添加screen相关接口
    screen: {
      lockOrientation(orientation) {
        if (plus.isH5) {
          // H5环境下可以使用Screen Orientation API
          try {
            if (screen.orientation && screen.orientation.lock) {
              screen.orientation.lock(orientation)
            }
          } catch (e) {
            console.log('Screen orientation API not supported')
          }
          return true
        }
      }
    },

    // 添加runtime相关接口
    runtime: {
      appid: 'H5_APP_ID',
      getProperty(appid, callback) {
        if (plus.isH5) {
          // H5环境下返回模拟版本信息
          callback({
            version: 'H5-1.0.0',
            name: 'H5版本'
          })
        }
      },
      quit() {
        if (plus.isH5) {
          // H5环境下可以关闭窗口或返回
          if (window.history.length > 1) {
            window.history.back()
          } else {
            window.close()
          }
        }
      }
    },

    // 添加key相关接口
    key: {
      addEventListener(event, callback) {
        if (plus.isH5) {
          // H5环境下监听返回键
          if (event === 'backbutton') {
            window.addEventListener('popstate', callback)
          }
        }
      },
      removeEventListener(event, callback) {
        if (plus.isH5) {
          if (event === 'backbutton') {
            window.removeEventListener('popstate', callback)
          }
        }
      }
    },

    // 添加nativeUI相关接口
    nativeUI: {
      showWaiting(message = '请稍候...', options = {}) {
        if (plus.isH5) {
          // 创建一个简单的loading提示
          let waiting = document.getElementById('h5-waiting')
          if (!waiting) {
            waiting = document.createElement('div')
            waiting.id = 'h5-waiting'
            waiting.style.cssText = `
              position: fixed;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -50%);
              background: rgba(0,0,0,0.7);
              color: white;
              padding: 10px 20px;
              border-radius: 5px;
              z-index: 10000;
            `
            document.body.appendChild(waiting)
          }
          waiting.textContent = message
          waiting.style.display = 'block'
        }
      },

      closeWaiting() {
        if (plus.isH5) {
          const waiting = document.getElementById('h5-waiting')
          if (waiting) {
            waiting.style.display = 'none'
          }
        }
      },

      toast(message) {
        if (plus.isH5) {
          mui.toast(message)
        }
      }
    },

    // 扩展camera相关接口
    camera: {
      getCamera() {
        return {
          supportedImageResolutions: ['1280x720'],
          supportedImageFormats: ['jpg'],
          captureImage(success, error, options) {
            // H5环境使用input file实现
            const input = document.createElement('input')
            input.type = 'file'
            input.accept = 'image/*'
            input.capture = 'camera'
            input.onchange = (e) => {
              const file = e.target.files[0]
              success(URL.createObjectURL(file))
            }
            input.click()
          }
        }
      }
    },

    // 扩展gallery相关接口  
    gallery: {
      pick(success, error, options) {
        const input = document.createElement('input')
        input.type = 'file'
        input.accept = 'image/*'
        input.multiple = options?.multiple
        input.onchange = (e) => {
          const files = Array.from(e.target.files)
          success(files.map(f => URL.createObjectURL(f)))
        }
        input.click()
      }
    }
  };

  // 重写 mui.plusReady
  if (window.mui && window.mui.plusReady) {
    const originalPlusReady = window.mui.plusReady;
    window.mui.plusReady = function (callback) {
      if (typeof callback === 'function') {
        callback();
      }
    };
  }

  // 触发 plusready 事件
  setTimeout(function () {
    const evt = document.createEvent('CustomEvent');
    evt.initCustomEvent('plusready', false, false, {});
    document.dispatchEvent(evt);
  }, 0);

  // 重写 mui.openWindow
  if (window.mui) {
    const originalOpenWindow = mui.openWindow;
    mui.openWindow = function (options) {
      if (!plus.isH5) return originalOpenWindow.call(mui, options);

      const { url, id, styles = {}, show = {} } = options;

      // 创建新窗口
      const webview = plus.webview.create(url, id, {
        position: 'fixed',
        top: '0',
        left: '0',
        width: '100%',
        height: '100%',
        zIndex: '999',
        ...styles
      });

      // 添加到页面
      document.body.appendChild(webview.iframe);

      // 如果需要显示动画效果
      if (show.aniShow) {
        webview.iframe.style.transition = 'all 0.3s';
        setTimeout(() => webview.show(), 50);
      } else {
        webview.show();
      }

      return webview;
    };
  }

})(window);